#include "log.h"
#include "u.h"
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>

Log::Log(QObject *parent)
    : QObject{parent}
{
    //"qt_sql_default_connection"
    if (QSqlDatabase::contains("qt_sql_default_connection")) {
        m_db = QSqlDatabase::database("qt_sql_default_connection");
    } else {
        m_db = QSqlDatabase::addDatabase("QSQLITE");
        m_db.setDatabaseName("lepure.db");
    }
    if (!m_db.open()) {
        qDebug() << __FILE__ << __LINE__ << "Error: Failed to connect database:" << m_db.lastError();
        return;
    } else {
        qDebug() << __FILE__ << __LINE__ << "Succeed to connect database." ;
    }
    initLog();
}

bool Log::isTableExists(const QString &tableName)
{
    QSqlQuery query(m_db);
    // 查询sqlite_master系统表，检查是否存在指定表
    // type='table' 表示只检查表，不包括视图等
    // name=? 是参数化查询，避免SQL注入和表名包含特殊字符的问题
    QString sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
    query.prepare(sql);
    query.addBindValue(tableName);

    if (!query.exec()) {
        qWarning() << "查询表是否存在失败：" << query.lastError().text();
        return false;
    }

    // 如果查询结果有记录，说明表存在
    bool r = query.next();
    query.clear();
    return r;
}

bool Log::initLog()
{
    if (!isTableExists("batch_data")){
        QSqlQuery query(m_db);
        QString createSql = "CREATE TABLE IF NOT EXISTS batch_data ("
                            "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                            "name TEXT,"
                            "speed TEXT,"
                            "weight TEXT,"
                            "temperature TEXT,"
                            "ph TEXT,"
                            "conductivity TEXT,"
                            "desc TEXT,"
                            "create_by TEXT,"
                            "create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
                            ");";
        query.prepare(createSql);
        if(!query.exec()) {
            qDebug() << __FILE__ << __LINE__ << "Error: Fail to create table." << query.lastError();
            return false;
        } else {
            qDebug() << __FILE__ << __LINE__ << "Table created!" << __DATE__;
        }
        query.clear();
    }
    return true;
}

bool Log::insertLog(QString name, QString speed, QString weight, QString temperature, QString ph, QString conductivity)
{
    QSqlQuery query(m_db);

    // 显式写入创建时间为本地当前时间
    QString insert = "insert into batch_data(name,speed,weight,temperature,ph,conductivity,create_by,create_time) values(:name,:speed,:weight,:temperature,:ph,:conductivity,'系统后台进程',datetime('now', 'localtime'))";
    query.prepare(insert);
    query.bindValue(":name", name);

    query.bindValue(":speed", speed);
    query.bindValue(":weight", weight);
    query.bindValue(":temperature", temperature);
    query.bindValue(":ph", ph);
    query.bindValue(":conductivity", conductivity);

    if(!query.exec()) {
        qDebug() << __FILE__ << __LINE__ << U::getThDt() << query.lastError() << insert;
    } else {
        qDebug() << __FILE__ << U::getThDt() << speed << ":" << weight <<":" << temperature <<":" << ph <<":" << conductivity;
    }
    query.clear();
    return true;
}
